import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'index',
    component: () => import('../views/front/IndexView.vue')
  }, {
    path: '/category',
    name: 'category',
    component: () => import('../views/front/CategoryView.vue')
  }, {
    path: '/usercenter',
    name: 'usercenter',
    component: () => import('../views/front/UserCenter.vue')
  }, {
    path: '/book/detail/:bookId',
    name: 'bookDetail',
    component: () => import('../views/front/BookDetail.vue')
  }, {
    path: '/book/catalog/:catalogId',
    name: 'bookCatalog',
    component: () => import('../views/front/ReadView.vue')
  },
  {
    path: '/admin/login',
    name: 'login',
    component: () => import('../views/admin/LoginView.vue')
  }, {
    path: '/home',
    name: 'home',
    redirect: '/home/about',
    component: () => import('../views/admin/HomeView.vue'),
    children: [{
      path: 'about',
      name: 'about',
      component: () => import('../views/admin/AboutView.vue')
    }, {
      path: 'userinfo',
      name: 'userinfo',
      component: () => import('../views/admin/userinfo/UserinfoList.vue')
    }, {
      path: 'ad',
      name: 'ad',
      component: () => import('../views/admin/ad/AdList.vue')
    }, {
      path: 'category',
      name: 'category',
      component: () => import('../views/admin/category/CategoryList.vue')
    }, {
      path: 'book',
      name: 'book',
      component: () => import('../views/admin/book/BookList.vue')
    }, {
      path: 'notice',
      name: 'notice',
      component: () => import('../views/admin/notice/NoticeList.vue')
    }, {
      path: 'feedback',
      name: 'feedback',
      component: () => import('../views/admin/feedback/FeedbackList.vue')
    }, {
      path: 'vip',
      name: 'vip',
      component: () => import('../views/admin/vip/VipList.vue')
    }]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  /* 此处为黑名单关键字，请求中只要包含以下关键字就必须登录后可用 */
  const blankSheets = ['home', 'opt']
  let go = true
  for (let i = 0; i < blankSheets.length; i++) {
    if (to.path.includes(blankSheets[i])) {
      go = false
      break
    }
  }
  if (go) { // 放行名单
    next()
  } else {
    if (Vue.$cookies.get('token')) {
      next()
    } else {
      if (to.path.includes('home')) {
        Vue.prototype.$alert('请先登录！', { type: 'warning' }).then(() => {
          next('/admin/login')
        })
      } else {
        Vue.prototype.$message.error('请登录后操作！')
      }
    }
  }
})

export default router
